<template id="swipe_num">
  <div style="clear:both; display: inline-block;">
    <template v-if="isIphone">
      <input type="text" className="form-control" v-model="num" @input="checkMoneyInput($event)" :disabled="!enable"/>
    </template>
    <template v-else>
      <div className="num-content" v-bind:style="{height:height?height:'3rem',opacity:enable?1:0.5}">
        <template v-for="(u,i) in nums">
          <div v-if="i == prefixFixed" className="num-list dot" v-bind:style="{width:width?width:'3rem'}">
            <table>
              <tr>
                <td v-bind:style="{border:'1px solid rgba(0,0,0,0) !important',height:height?height:'3rem'}">.</td>
              </tr>
            </table>
          </div>
          <div className="num-list"
               v-on:touchstart="startMoving(i,$event)"
               v-on:touchmove.stop.prevent="moving"
               v-on:touchend="stopMoving()"
               v-bind:style="{transform:'translateY('+offsetTops[i]+'px)',transition:tranAnimations[i],width:width?width:'3rem'}">
            <div ref="first">
              <table>
                <tbody>
                <tr v-for="j in 10">
                  <td v-bind:style="{border:'none !important',height:height?height:'3rem'}">{{ j - 1 }}</td>
                </tr>
                </tbody>
              </table>
            </div>
            <div>
              <table>
                <tbody>
                <tr v-for="j in 10">
                  <td v-bind:style="{border:'none !important',height:height?height:'3rem'}">{{ j - 1 }}</td>
                </tr>
                </tbody>
              </table>
            </div>
          </div>
        </template>
      </div>
    </template>
  </div>
</template>

<script>
import util from '@/util'
import {reactive} from "vue";

export default {
  name: "swipe_num_tool",
  data() {
    return {
      movingStates: reactive([]),
      isPhone: false,
      offsetTops: reactive([]),
      screenY: 0,
      listHeight: 0,
      rowHeight: 0,
      tranAnimations: reactive([]),
      currIndex: 0,
      nums: reactive([]),
      num: 0,
      //电脑版浏览器和iphone的safari都为true
      isIphone: false,
      enable: true,
      lastNum: "",

      outNum: 0,
    }
  },
  //type : string, number
  props: ['prefixFixed', 'afterFixed', 'numVal', 'height', 'width', "type"],
  mounted() {
    this.usingType = this.type || "number"
    this.isIphone = !util.isUsefulPhone()
    var prefixFixed, afterFixed
    if (this.prefixFixed) {
      prefixFixed = parseInt(this.prefixFixed)
    } else {
      prefixFixed = 1
    }
    if (this.afterFixed) {
      afterFixed = parseInt(this.afterFixed)
    }
    var nums = []
    for (var i = 0; i < (prefixFixed + afterFixed); i++) {
      this.movingStates.push(false)
      this.offsetTops.push(0)
      this.tranAnimations.push("")
      nums.push(0)
    }
    this.nums = nums;
    // if (this.isIphone && this.numVal === "0") {
    //   this.num = ""
    // } else {
    //   this.num = this.numVal
    // }
    this.setNum(this.numVal, true)

  },
  watch: {
    outNum(newVal) {
      console.log(newVal + ' / ' + this.num)
      this.$emit("update", this.num)
    }
  },
  methods: {
    checkMoneyInput(e) {
      if (!this.numReg) {
        this.numReg = new RegExp("^(\\d{1," + this.prefixFixed + "}\\.?(\\.\\d{1," + this.afterFixed + "})?)$", "g")
      }
      this.numReg.lastIndex = 0
      if (this.num === '' || this.numReg.test(this.num)) {
        this.lastNum = this.num
      } else {
        var selectStart = e.target.selectionStart
        var selectEnd = e.target.selectionEnd
        this.num = this.lastNum
        if (e.target.setSelectionRange) {
          setTimeout(function () {
            e.target.setSelectionRange(selectStart - 1, selectEnd - 1)
          }, 10)
        }
      }
    },
    setEnabled(state) {
      this.enable = !!state
    },
    getNum() {
      return this.num || 0
    },
    getResetNum() {
      return this.lastNum || 0;
    },
    resetNum() {
      this.setNum(this.lastNum||0)
    },
    setNum(num, isDisableWatch) {
      if (!this.numReg) {
        var str = "^\\d{0," + this.prefixFixed + "}";
        if (this.afterFixed && parseInt(this.afterFixed) > 0) {
          str += "((\\.?)|((\\.\\d{1," + this.afterFixed + "})?))";
        }
        str += "$";
        this.numReg = new RegExp(str, "g")
      }
      this.numReg.lastIndex = 0
      if (!this.numReg.test(num + "")) {
        return
      }
      if (this.isIphone) {
        this.num = num
      } else {
        this.N = num
        let id = window.setInterval(() => {
          num = this.N
          if (this.listHeight == 0) {
            var f = this.$refs.first
            if (f && f[0]) {
              this.listHeight = f[0].offsetHeight
              this.rowHeight = this.listHeight / 10
            } else {
              window.clearInterval(id)
            }
            return
          }
          window.clearInterval(id)
          var nums = []
          var num = (num != null ? num : this.num) + ""
          var size = this.prefixFixed
          if (!size) {
            size = 1
          }
          if (size < 1) {
            size = 1
          }
          var index = num.indexOf(".")
          if (index == -1) {
            index = num.length - 1
          } else {
            index = index - 1;
          }
          for (var i = index, j = 0; j < size; i--, j++) {
            nums.unshift(i >= 0 ? parseInt(num[i]) : 0)
          }
          size = this.afterFixed
          if (!size) {
            size = 0
          }
          if (size < 0) {
            size = 0
          }
          if (size > 0) {
            index = num.indexOf(".")
            if (index == -1) {
              for (let i = 0; i < size; i++) {
                nums.push(0)
              }
            } else {
              for (let i = index + 1, j = 0; j < size; i++, j++) {
                nums.push(i < num.length ? parseInt(num[i]) : 0)
              }
            }
          }
          this.nums = nums
          for (let i in nums) {
            this.currIndex = parseInt(i)
            // this.$set(this.offsetTops, i, -nums[i] * this.rowHeight)
            this.offsetTops[i] = -nums[i] * this.rowHeight
            this.stopMoving(isDisableWatch)
          }
        }, 100)
      }
    },
    startMoving(i, e) {
      if (!this.enable) return
      if (this.listHeight == 0) {
        var f = this.$refs.first
        this.listHeight = f[0].offsetHeight
        this.rowHeight = this.listHeight / 10
      }
      this.currIndex = i
      var offsetTop = this.offsetTops[this.currIndex]
      // this.$set(this.tranAnimations, this.currIndex, '')
      this.tranAnimations[this.currIndex] = ''
      if (e.targetTouches) {
        this.screenY = e.targetTouches[0].screenY - offsetTop
        this.isPhone = true
      } else {
        this.screenY = e.screenY - offsetTop
        this.isPhone = false
      }
      // this.$set(this.movingStates, this.currIndex, true)
      this.movingStates[this.currIndex] = true
    },
    moving(e) {
      if (!this.enable) return
      if (this.movingStates[this.currIndex]) {
        var offsetTop = (this.isPhone ? e.targetTouches[0].screenY : e.screenY) - this.screenY
        if (offsetTop >= 0) {
          offsetTop = -this.listHeight + offsetTop
        } else if (offsetTop < -this.listHeight) {
          offsetTop = this.listHeight + offsetTop
        }
        // this.$set(this.offsetTops, this.currIndex, offsetTop)
        this.offsetTops[this.currIndex] = offsetTop
      }
    },
    stopMoving(isDisableWatch) {
      if (!this.enable) return
      // this.$set(this.movingStates, this.currIndex, false)
      this.movingStates[this.currIndex] = false
      // this.$set(this.tranAnimations, this.currIndex, 'transform 0.5s')
      this.tranAnimations[this.currIndex] = 'transform 0.5s'
      var offsetTop = this.offsetTops[this.currIndex]
      var x = parseFloat(offsetTop) % this.rowHeight
      var n = -parseInt(offsetTop / this.rowHeight)
      var line = -this.rowHeight / 2
      if (x <= line) {
        offsetTop = offsetTop - this.rowHeight - x
        n++
        if (n > 9) {
          n = 0;
        }
      } else {
        offsetTop = offsetTop - x
      }
      // this.$set(this.offsetTops, this.currIndex, offsetTop)
      this.offsetTops[this.currIndex] = offsetTop
      // this.$set(this.nums, this.currIndex, n)
      this.nums[this.currIndex] = n
      var s = this.nums.slice(0, this.prefixFixed).join("");
      if (this.afterFixed && parseInt(this.afterFixed) > 0) {
        s += "." + this.nums.slice(this.prefixFixed).join("")
      }
      let currNum
      if (this.usingType === 'number') {
        currNum = parseFloat(s)
      } else {
        currNum = s
      }
      this.lastNum = this.num
      this.num = currNum
      if (!isDisableWatch) {
        this.outNum++
      }
    }
  }
}
</script>

<style lang="css" scoped>
.num-content {
  overflow: hidden;
  display: flex;
  flex-wrap: nowrap;
  justify-content: flex-end;
  align-content: flex-start;
}

.num-content .num-list {
  display: inline-block;
}

.num-content .num-list table {
  text-align: center;
  width: 100%;
}

.num-content .dot {
  align-content: flex-end;
}

</style>